package com.gtguigu.pojo;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;

public class Dmo4jTest {

    @Test
    public void test1()throws Exception{
    //创建一个saxReader输入流，去读取xml配置文件，生成Document对象
    SAXReader saxReader=new SAXReader();
    try {
        Document document=saxReader.read("src/books.xml");
        System.out.println(document);
    }catch (Exception e) {
        e.printStackTrace();
    }

}
@Test
    public void test2() throws Exception {
        //1.读取books.xml文件
    SAXReader saxReader = new SAXReader();
    //在Junit测试中，相对路径是从模块名开始算
    Document document = saxReader.read("src/books.xml");
    //2通过Document对象获取根元素
    Element rootElement = document.getRootElement();
    //3.通过根元素获取book标签对象
    List<Element> books = rootElement.elements();
    //4遍历，处理每个book标签转换为book类
    for (Element book : books) {
        //asXml()把标签对象，转换为标签字符串
        Element nameElement = book.element("name");
        String nameText=nameElement.getText();
        //直接获取指定
        String priceText = book.elementText("price");
        String authorText = book.elementText("author");
        String snValue = book.attributeValue("sn");//获取属性值
        System.out.println(new Book(snValue,nameText,Double.parseDouble(priceText),authorText));
    }
    }
}